import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { ServiceResult, Constant } from '../../../../core/constant';
import { ProductSkuEditV2Component } from '../../../../shared/component/product-sku-edit-v2/product-sku-edit-v2.component';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {plopService} from "../../../../service/plop/plop.service";

@Component({
  selector: 'plop-add',
  templateUrl: './plop-add.component.html',
  styleUrls: ['./plop-add.component.less']
})
export class plopAddComponent implements OnInit, OnDestroy {

  product:  any = {
    id:null,
    bpmStatus:null,
    orderNo:null,
    cusName:null,
    cusMobile:null,
    overduePeriod:null,
    overdueAmount:null,
    penaltyAmount:null,
    overdueUser:null,
    overdueContent:null,
    overdueRemark:null
  };
  bpmStatus =  [{text: 'M1', value: 'M1'}, {text: 'M2', value: 'M2'}, {text: 'M3', value: 'M3'}, {text: 'M4', value: 'M4'}, {text: 'M5', value: 'M5'}];
  plo_mes=[];
  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;
  profileForm: FormGroup;

  saleing = false;
  proNos = [];
  cusrIdtypes = [];
  cusGenders = [];
  cusMaritalStatuss = [];
  cusDeus = [];
  cusEthnicals = [];
  // bpmStatus =  [{text: '未处理', value: '1'}, {text: '已处理', value: '10'}];
  // seriess = [];
  // proTypes = [];
  // frameTypes = [];
  // isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  // isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];
  @ViewChild("skuEdit2") skuEdit2: ProductSkuEditV2Component;
  private sub: any;


  avatarUrl: string;
  loading = false;
  uploadUrl = '';
  avatarParam = { type: 'Avatar', userId: ''};


  constructor(
    private plopService: plopService,
    public setting: SettingsService,

    private msg: NzMessageService,
    private modalService: NzModalService,
    private productService: ProductService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private router: Router,
    private cnt: Constant,
    private comm: CommService
  ) {
    this.titleService.setTitle("添加");

  }

  ngOnInit(): void {

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.orderNo = params["id"]
      console.log("this.product.id****************"+this.product.id);
      // 获取商品详情
      this.getProductInfo();
    });
this.loadplo_mes();

    setTimeout(() => {
        this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);

  }

  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }


  // 加载处理类型
  loadplo_mes() {
    this.plo_mes = [];
    this.comm.getType("plo_me").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.plo_mes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  reset(i) {

  }

  getProductInfo() {
    this.productService.getProduct(this.product.orderNo).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;




    })
  }

  save() {


    let fxjPlOveroper = {
      createBy:this.setting.user.username,
      sysOrgCode:this.setting.user.sysorgCode,
      id:this.product.id,
      bpmStatus:this.product.bpmStatus,
      orderNo: this.product.orderNo,
      cusName: this.product.cusName,
      cusMobile: this.product.cusMobile,
      // cusrIdtype: this.product.cusrIdtype,
      // cusIncard: this.product.cusIncard /*No show*/,
      overduePeriod: this.product.overduePeriod /*No show*/,
      // cusIdValidto: this.product.cusIdValidto /*No show*/,
      overdueAmount: this.product.overdueAmount,
      penaltyAmount: this.product.penaltyAmount,
      overdueUser:this.setting.user.username,
      overdueContent:this.product.overdueContent,
      overdueRemark:this.product.overdueRemark


    };
    // 调用接口
    this.loading = true;
    this.plopService.addPro(fxjPlOveroper).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.loading = false;
      if (data.ok === true) {
           this.msg.success("添加成功");
          this.emit.sendMessage("RELOAD_GOODS_LIST");

      } else {
        this.msg.error(data['message']);
      }
    })
  }

  back() {
    this.router.navigate(['/prod/product/80']);
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`No support: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.warning('The pic file not more than 2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

}
